package pre;

import java.util.HashMap;
import java.util.Map;

public class Trie {
    static class TrieNode {
        char val;
        Map<Character, TrieNode> children = new HashMap<>();
        boolean end;

        TrieNode() {}
        TrieNode(char val) {this.val = val;}
    }

    TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        TrieNode node = root;
        for (char c : word.toCharArray()) {
            node.children.computeIfAbsent(c, k -> new TrieNode(c));
            node = node.children.get(c);
        }
        node.end = true;
    }

    TrieNode getNode(String str) {
        TrieNode node = root;
        for (char c : str.toCharArray()) {
            TrieNode next = node.children.get(c);
            if (null == next)
                return null;

            node = next;
        }
        return node;
    }
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = getNode(word);
        return node != null && node.end;
    }

    /** Returns if there is any word in the trie that starts with the
     given prefix. */
    public boolean startsWith(String prefix) {
        return getNode(prefix) != null;
    }
}

